package com.pinion.controller.API;

import com.base.config.Constant;
import com.base.model.authority.T_User;
import com.base.model.log.T_Loginlog;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.pinion.interception.MBInterceptor;
import com.pinion.json.OrderItemVO;
import com.pinion.json.OrderVO;
import com.pinion.model.*;
import com.pinion.util.JSONUtil;
import com.zh_new.annotation.RouteBind;
import com.zh_new.util.IpAddr;
import com.zh_new.util.Pwd;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.regexp.RE;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 移动客户端同步接口
 */
@RouteBind(path = "/API/MB")
public class MBController extends Controller {

    private static final Logger log = Logger.getLogger(MBController.class);

    @ClearInterceptor(ClearLayer.ALL)
    //@Before(MBInterceptor.class)
    public void index() {
        //获取客户端传过来的信息
//        String inJsonStr = HttpKit.readIncommingRequestData(getRequest());
//        try {
//            //解析成Map
//            Map<String, Object> requestJson = new ObjectMapper().readValue(inJsonStr, Map.class);
//            requestJson.size();
//
//            System.out.print(requestJson);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        Integer update_type = getParaToInt("update_type");
        if (null == update_type)
            return;
        //控制流转
        switch (update_type) {
            case Constant.UPDATE_COMMODITIES:
                this.updateCommodities();
                break;
            case Constant.UPDATE_BRAND:
                this.updateBrand();
                break;
            case Constant.UPDATE_CLASSIFICATION:
                this.updateGoodsType();
                break;
            case Constant.UPDATE_REGION_PRICE:
                this.updateRegionPrice();
                break;
            case Constant.UPDATE_REGION_CODE:
                this.updateRegionCode();
                break;
            case Constant.UPDATE_PICTURE:
                this.updatePicture();
                break;
            case Constant.UPDATE_ORDER:
                this.updateOrder();
                break;
            case Constant.UPDATE_CLASSIFICATION_PICTURE:
                this.updateGoodsTypePicture();
                break;
            case Constant.UPDATE_SPRECIAL_PICTURE:
                this.updateSpecialPicture();
                break;
            default:
                break;
        }
    }

    /**
     * 更新商品(t_goods)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=1&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updateCommodities() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_COMMODITIES);                            //起始时间戳
        List<T_Goods> goodsList = T_Goods.dao.find("SELECT * FROM t_goods WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", goodsList);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }


    /**
     * 更新品牌(t_brand)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=4&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updateBrand() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_BRAND);                            //起始时间戳
        List<T_Brand> brandList = T_Brand.dao.find("SELECT * FROM t_brand WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", brandList);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }

    /**
     * 更新商品类型(t_goods_type)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=3&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updateGoodsType() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_CLASSIFICATION);                            //起始时间戳
        List<T_Goods_Type> list = T_Goods_Type.dao.find("SELECT * FROM t_goods_type WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", list);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }

    /**
     * 更新区域价格(t_region_price)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=5&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updateRegionPrice() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_REGION_PRICE);                            //起始时间戳
        List<T_Region_Price> list = T_Region_Price.dao.find("SELECT * FROM t_region_price WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", list);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }

    /**
     * 更新区域编码(t_region_code)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=8&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updateRegionCode() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_REGION_CODE);                            //起始时间戳
        List<T_Region_Code> list = T_Region_Code.dao.find("SELECT * FROM t_region_code WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", list);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }

    /**
     * 更新商品图片(t_goods_picture)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=2&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updatePicture() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_PICTURE);                            //起始时间戳
        List<T_Goods_Picture> list = T_Goods_Picture.dao.find("SELECT * FROM t_goods_picture WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", list);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }

    /**
     * 更新商品类型图片(t_goods_type_picture)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=9&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updateGoodsTypePicture() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_COMMODITIES);                            //起始时间戳
        List<T_Goods_Type_Picture> list = T_Goods_Type_Picture.dao.find("SELECT * FROM t_goods_type_picture WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", list);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }

    /**
     * 更新特殊商品图片(t_special_picture)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=10&auth_id=235AC30A593DFE95DE6BCC56586C23D6
     */
    public void updateSpecialPicture() {
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_COMMODITIES);                            //起始时间戳
        List<T_Goods_Type_Picture> list = T_Goods_Type_Picture.dao.find("SELECT * FROM t_goods_type_picture WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
        setAttr("update_data", list);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }

//    @SuppressWarnings("unchecked")
//    private <T extends Model<T>> List<T> getUpdateDate(T t, String dbtable) {
//        Integer user_id = getUserId();
//        String start_timestamp = getPara("client_timestamp");      //起始时间戳
//        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
//        //获取当前用户客户端更新的记录
//        Record clientUpdateItem = Db.findFirst("SELECT * FROM t_client_update WHERE user_id=? AND update_type=?", user_id, Constant.UPDATE_COMMODITIES);
//        if (null == clientUpdateItem) {
//            T_Client_Update clientUpdateModel = new T_Client_Update();
//            clientUpdateModel.set("user_id", user_id);
//            clientUpdateModel.set("update_type", Constant.UPDATE_COMMODITIES);
//            clientUpdateModel.set("end_timestamp", end_timestamp);
//            clientUpdateModel.save();
//            //重置起始时间戳
//            start_timestamp = "1970-01-01 00:00:00";
//        }
////        List<T> resultList = T.dao.find("SELECT * FROM " + dbtable + " WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);
////        return resultList;
//    }

    private Integer getUserId() {
        return getAttrForInt("auth_user_id");     //MBInterceptor中获取的当前用户的user_id值
    }

    private String getStartTimestamp(Integer user_id, String end_timestamp, Integer updateType) {
        String start_timestamp = getPara("client_timestamp");      //起始时间戳
        //获取当前用户客户端更新的记录
//        Record clientUpdateItem = Db.findFirst("SELECT * FROM t_client_update WHERE user_id=? AND update_type=?", user_id, Constant.UPDATE_COMMODITIES);
        T_Client_Update clientUpdateItem = T_Client_Update.dao.getClientUpdate(user_id, updateType);
        if (null == clientUpdateItem) {
            T_Client_Update clientUpdateModel = new T_Client_Update();
            clientUpdateModel.set("user_id", user_id);
            clientUpdateModel.set("update_type", updateType);
            clientUpdateModel.set("end_timestamp", end_timestamp);
            clientUpdateModel.save();
        } else {
            //TODO:判断是否start_timestamp有值，若参数start_timestamp无值且当前用户又有T_Client_Update记录是否需要抛异常
//            start_timestamp = clientUpdateItem.get("end_timestamp");
            clientUpdateItem.set("end_timestamp", end_timestamp);
            clientUpdateItem.update();
        }
        if (null == start_timestamp || 0 == start_timestamp.trim().length()) {
            //重置起始时间戳
            start_timestamp = "1970-01-01 00:00:00";
        }

        return start_timestamp;
    }

    /**
     * 更新商品订单(t_order)
     * http://localhost:8080/API/MB?client_timestamp=&update_type=6&auth_id=6056415BB56C64786398254C51FBBE67
     */
    @Before(Tx.class)
    public void updateOrder() {
        //解析传来的json
        String jsonString = getPara("update_data");
        if (null != jsonString) {
            JSONObject joOrders = JSONObject.fromObject(jsonString);
            JSONArray jnOrder = joOrders.getJSONArray("orders");
            for (int i = 0; i < jnOrder.size(); i++) {
                //TODO:解析order list json
                JSONObject joOrder = JSONObject.fromObject(jnOrder.getString(i));
                try {
                    OrderVO orderVO = (OrderVO) JSONUtil.fromJsonToJava(joOrder, OrderVO.class);
//                    T_Order object = (T_Order)JSONUtil.fromJsonToJava(joOrder, T_Order.class);
                    //检查状态字段，若为"已提交"状态则为新订单
                    if (Constant.ORDER_STATUS_COMMITTED == orderVO.getStatus()) {

                        T_Order order = orderVO.setToObj();
                        order.save();

                        JSONArray jnOrderItem = joOrder.getJSONArray("items");
                        for (int j = 0; j < jnOrderItem.size(); j++) {
                            //TODO:解析order item list json
                            JSONObject joOrderItem = JSONObject.fromObject(jnOrderItem.getString(i));
                            try {
                                OrderItemVO orderItemVO = (OrderItemVO) JSONUtil.fromJsonToJava(joOrderItem, OrderItemVO.class);
                                T_Order_Item orderItem = orderItemVO.setToObj(order.getInt("id"), order.getInt("create_user"));
                                orderItem.save();
                            } catch (Exception e) {
                                e.printStackTrace();
                                log.error("[OrderItem], json转model转换出错！", e);
                            }
                        }
                    } else {
                        //根据订单编号获取订单
                        int orderStatus = joOrder.getInt("status");
                        String orderNum = joOrder.getString("number");
                        T_Order order = T_Order.dao.getByNumber(orderNum);

                        //若客户端的订单状态"大于"服务端,则修改服务端状态
                        if(orderStatus > order.getInt("status")) {
                            order.set("status", orderStatus);
                            order.save();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("[Order],json转model转换出错！", e);
                }


            }
        }


        List<OrderVO> orderVOList = new ArrayList<OrderVO>();
        //获取当前用户的user_id
        Integer user_id = getUserId();
        String end_timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());         //终止时间戳
        String start_timestamp = getStartTimestamp(user_id, end_timestamp, Constant.UPDATE_ORDER);                            //起始时间戳
        List<T_Order> list = T_Order.dao.find("SELECT * FROM t_order WHERE last_date > ? AND last_date < ?", start_timestamp, end_timestamp);

        for (T_Order l : list) {
            //获取当前订单的所有OrderItem
            List<T_Order_Item> iList = T_Order_Item.dao.find("SELECT * FROM t_order_item WHERE order_id = ?", l.get("id"));
//            l.setItems(iList);

            OrderVO orderVO = new OrderVO();
            orderVO.genFromObj(l);

            List<OrderItemVO> items = new ArrayList<OrderItemVO>();
            for(T_Order_Item iL : iList) {
                OrderItemVO orderItemVO = new OrderItemVO();
                orderItemVO.genFromObj(iL);
                items.add(orderItemVO);
            }

            orderVO.setItems(items);
            orderVOList.add(orderVO);
        }

//        setAttr("update_data", list);
        setAttr("update_data", orderVOList);
        setAttr("end_timestamp", end_timestamp);
        renderJson();
    }


    /**
     * 客户端用户登录
     * http://localhost:8080/API/MB/login?username=root&password=root
     */
    @ClearInterceptor(ClearLayer.ALL)
    public void login() {
        String username;
        String password;
        if (null == getPara("username") || null == getPara("password") || getPara("username").trim().equals("") || getPara("password").trim().equals("")) {
            setAttr("auth", false);
            setAttr("message", "用户名或者密码未输入!");
            renderJson();
            return;
        }
        username = getPara("username");
        password = getPara("password");
        RE re = new RE("^[A-Za-z0-9]+$");
        if (!re.match(username) || !re.match(password)) {
            setAttr("auth", false);
            setAttr("message", "alert('输入错误,用户名和密码为英文字母和数字组合!')");
            renderJson();
            return;
        }
        T_User user = T_User.dao.exists(username);
        //判断用户是否存在
        if (null == user) {
            setAttr("auth", false);
            setAttr("message", "不存在该用户!");
            renderJson();
            return;
        }
        //判断用户密码是否正确
        if (!user.get("pwd").equals(Pwd.encrypt(user.get("id") + password))) {
            setAttr("auth", false);
            setAttr("message", "用户密码错误!");
            renderJson();
            return;
        }
        //判断当前账户是否可用
        if (user.getStr("usable").equals("1")) {
            String auth_id = getSession().getId();
            T_Loginlog oldLoginlog = T_Loginlog.dao.getBySession(auth_id);
            //判断是否超时
            if (null != oldLoginlog) {
                // && oldLoginlog.isLoginTimeOut(auth_id, Constant.CLIENT_MB //超时
                //UPDATE(dltime字段)
                oldLoginlog.set("dltime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //重置登录时间
                oldLoginlog.set("u_id", user.get("id"));    //更新用户id，以免被篡改
                oldLoginlog.update();
            } else {
                T_Loginlog loginlog = new T_Loginlog();
                loginlog.set("sessionId", auth_id);
                loginlog.set("dlms", "正常");
                loginlog.set("dltime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //重置登录时间
                loginlog.set("u_id", user.get("id"));
                loginlog.set("ip", IpAddr.getIpAddr(getRequest()));
                loginlog.save();
            }

            setAttr("auth", true);
            setAttr("staff_id", user.get("staff_id"));       //工号
            setAttr("auth_id", auth_id);
            renderJson();
        } else {
            setAttr("auth", false);
            setAttr("message", "用户[" + username + "]已被禁用!");
            renderJson();
            return;
        }
    }


    /*
    http://localhost:8080/API/MB/test
     */
    @ClearInterceptor(ClearLayer.ALL)
    public void test() {
//        List<String> str = new ArrayList<String>();
//        str.add("1");
//        str.add("2");
//        str.add("3");
//        setAttr("list", str);

        T_Loginlog oldLoginlog = T_Loginlog.dao.getBySession("E578F006491D19A1D55EFEDA8E92BF64");
        Date dlTime = new Date(oldLoginlog.getDate("dltime").getTime());
        Date curTime = new Date();

        long time1 = dlTime.getTime();
        long time2 = curTime.getTime();
        long test = (long) (Math.abs(time2 - time1) * 0.001);


        setAttr("username", "admin");
        setAttr("password", "admin");
        renderJson();
    }


}
